const request = require('request-promise')
const config = require('config')
const cacheService = require('services/cache')
const appId = config.wechat.appid
const secret = config.wechat.secret
const KEY = 'access_token'

const get = async () => {
  const token = await cacheService.get(KEY)
  if (token) {
    return token
  } else {
    return await refresh()
  }
}

const refresh = async () => {
  const result = await request.get({json:true,uri:`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${secret}`})
  const token = result.access_token
  const expires_in = result.expires_in - 60 * 3
  await cacheService.set(KEY, token, expires_in)
  return token
}

module.exports = {
  get,
  refresh
}